﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args.WizardForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.DynamicForm.PlugIn.WizardForm;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Orm.DataEntity;
using System;
using System.ComponentModel;

namespace LM.CB.K3Cloud.Plugin
{
    /// <summary>
    /// 预算成本导航表单插件
    /// </summary>
    /// <remarks>
    /// 功能：1.校验组织，年，月必填 
    ///      2.根据组织，年，月，校验关于bom\材料预算价格表\工艺路线\费率表是否有数据
    ///      3.
    /// 创建人：吴振金
    /// 创建日期：2024-03-25
    /// </remarks>
    [Description("预算成本导航表单插件")]
    [Kingdee.BOS.Util.HotUpdate]
    public class BudgetCostBillPlugin : AbstractWizardFormPlugIn
    {
        string OrgId = "";
        string year = "";
        string Month = "";
        string fPriceType = "";//成本价格类型
        string fexpTypeId = "";//费率id
        string fMtrlPriceId = "";//材料表id
        string fbomSet = "";//自定义bom
        private ProgressBar _progressBar = null;//进度条

        //临时表
        string tempFilterTable = ""; 
        //private int _progressValue = 0;//当前进度
        private const string ProcessRateValue = "ProcessRateValue";
        bool islock = false;

        public override void OnInitialize(InitializeEventArgs e)
        {
            this._progressBar = this.View.GetControl<ProgressBar>("F_RDLV_ProgressBar");

        }

        /// <summary>
        /// 操作步骤切换前事件
        /// </summary>
        /// <param name="e"></param>
        public override void WizardStepChanging(WizardStepChangingEventArgs e)
        {
            if (e.UpDownEnum == 1)
            {
                // 校验第一步组织，年度，月份信息内容是否填写
                if (e.OldWizardStep.Key.Equals("FWizard0", StringComparison.OrdinalIgnoreCase))
                {
                    DynamicObject Org = this.View.Model.DataObject["F_RDLV_OrgId"] as DynamicObject;
                    if (Org != null)
                    {
                        OrgId = Org["ID"].ToString(); // 组织编码
                    }
                    year = Convert.ToString(this.Model.GetValue("F_RDLV_year"));
                    Month = Convert.ToString(this.Model.GetValue("F_RDLV_Month"));
                    fPriceType = Convert.ToString(this.Model.GetValue("F_QLTK_PriceType"));
                    fexpTypeId = (this.Model.GetValue("F_QLTK_expPrice") as DynamicObject)?["id"].ToString()??"";
                    fMtrlPriceId = (this.Model.GetValue("F_QLTK_materialPrice") as DynamicObject)?["id"].ToString() ?? "0";
                    fbomSet= (this.Model.GetValue("F_QLTK_bom") as DynamicObject)?["id"].ToString() ?? "0";
                    //处理产品，构建临时表，存储选择的产品
                    tempFilterTable = ServiceHelper.GetService<IDBService>().CreateTemporaryTableName(this.Context, 1)[0];
                    string strSql = string.Format(@"/*dialect*/ create table {0}
                                (fmaterial int )", tempFilterTable);
                    DBUtils.Execute(this.Context, strSql);

                    //遍历选择的物料，拼接，
                    DynamicObjectCollection collection = this.Model.GetValue("F_QLTK_Product")as DynamicObjectCollection;
                    if(collection.Count>0)
                    {
                        string strTable = "/*dialect*/insert into " + tempFilterTable + " values ";
                        foreach (var item in collection)
                        {
                            //获取物料id
                            string mtrlid = item["F_QLTK_Product_id"].ToString();
                            strTable += string.Format("({0})", mtrlid);
                            if (collection.IndexOf(item) < collection.Count - 1)
                            {
                                strTable += ",";
                            }
                        }
                        DBUtils.Execute(this.Context, strTable);
                    }
                    if (string.IsNullOrWhiteSpace(OrgId) || string.IsNullOrWhiteSpace(year)
                        || string.IsNullOrWhiteSpace(Month)||string.IsNullOrWhiteSpace(fPriceType)
                        || string.IsNullOrWhiteSpace(fexpTypeId) )
                    {
                        this.View.ShowWarnningMessage("先维护组织，年度，月份,价值类型,费率单价信息!");
                        e.Cancel = true;
                        return;
                    }
                    //判断年初不变价成本是否删除，如果未删除给出提示，其他价格类型不必删除
                    if(fPriceType=="年初不变价成本")
                    {
                        strSql = $@"select fid from RDLV_t_BugCostTree where F_RDLV_Year={year}
	                    and  F_RDLV_ORGID={OrgId} and F_QLTK_PriceType='年初不变价成本'";
                        DynamicObjectCollection dt = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                        if(dt != null && dt.Count>0)
                        {
                            this.View.ShowWarnningMessage("请先删除年初不变价预算，再计算!");
                            e.Cancel = true;
                            return;
                        }
                    }else//其他价格类型，产品必须录入
                    {
                        if(collection.Count<=0)
                        {
                            this.View.ShowWarnningMessage("请输入产品信息!");
                            e.Cancel = true;
                            return;
                        }
                    }
                    
                }
                // 合法性校验只要有不通过时点击下一步触发提示
                if (e.OldWizardStep.Key.Equals("FWizard1", StringComparison.OrdinalIgnoreCase) && islock)
                {
                    this.View.ShowWarnningMessage("合法新检测有结果有不通过数据请先处理");
                    e.Cancel = true;
                    return;
                }
            }
        }

        /// <summary>
        /// 操作步骤切换后事件
        /// </summary>
        /// <param name="e"></param>
        /// <summary>
        /// 操作步骤切换后事件
        /// </summary>
        /// <param name="e"></param>
        public override void WizardStepChanged(WizardStepChangedEventArgs e)
        {
            base.WizardStepChanged(e);
            if (e.UpDownEnum == 1)
            {
                if (e.WizardStep.ContainerKey == "F_RDLV_STEP2")
                {    //查询bom\材料预算价格表\工艺路线\费率表是否有对应数据        
                    string sql = $@"/*dialect*/exec DEV_YSCBLegitimacyVerification @F_RDLV_ORGID={OrgId} ,@F_RDLV_YEAR={year},
                    @F_RDLV_MONTH={Month},@fpriceType='{fPriceType}'";
                    DynamicObjectCollection dy = DBUtils.ExecuteDynamicObject(Context, sql.ToString());
                    if (dy.Count > 0)
                    {
                        this.View.Model.DeleteEntryData("F_RDLV_CheckEntity");
                        foreach (var dylitem in dy)
                        {
                            this.Model.CreateNewEntryRow("F_RDLV_CheckEntity");//合法性检测单据体赋值
                            this.Model.SetValue("F_RDLV_CheckItem", Convert.ToString(dylitem["JCX"]), dy.IndexOf(dylitem)); //检查项
                            this.Model.SetValue("F_RDLV_CheckResult", Convert.ToString(dylitem["JCJG"]), dy.IndexOf(dylitem)); //检查结果
                            this.Model.SetValue("F_RDLV_ShowRuslt", Convert.ToString(dylitem["MX"]), dy.IndexOf(dylitem)); //明细
                            if (Convert.ToString(dylitem["JCJG"]) == "1")//合法性检验有不通过
                            {
                                islock = true;
                            }
                        }
                        this.View.UpdateView("F_RDLV_CheckEntity");
                    }
                }

                if (e.WizardStep.ContainerKey == "F_RDLV_STEP3")
                {
                    this.View.GetControl("F_RDLV_YSCBCX").Visible = false;//隐藏链接
                    // 启动进度条，每个2s，到服务器获取一次进度。
                    // 如果进度达到了100，则自动停止
                    this._progressBar.Start(2);
                    // 开启一个新线程，处理需要长时间进行的业务
                    Kingdee.BOS.KDThread.MainWorker.QuequeTask(this.Context,
                        () =>
                        {
                            try
                            {
                                // TODO: 异步处理
                                string sql = $@"/*dialect*/
                                exec dev_p_getProductCost @forgid='{OrgId}',@fyear='{year}',@fmonth='{Month}',
                                @fpriceType='{fPriceType}',@FexpPriceId={fexpTypeId},@fMtrlPriceId={fMtrlPriceId},
                                @ProductTable='{tempFilterTable}',@fbomSet={fbomSet}";
                               
                                DBUtils.Execute(Context, sql);
                            }
                            catch (Exception ex)
                            {
                                this.View.ShowErrMessage(ex.Message);
                            }
                            finally
                            {
                                this.View.Session["ProcessRateValue"] = 100;
                                this.View.SendDynamicFormAction(this.View);
                            }
                        },
                        new Action<Kingdee.BOS.KDThread.AsynResult>((ar) =>
                        {
                            if (ar.Success == false && ar.Exception != null)
                            {
                                return;
                            }
                        }));
                }
            }
        }

        /// <summary>
        /// 进度条，咨询进度
        /// </summary>
        /// <param name="e"></param>
        public override void OnQueryProgressValue(QueryProgressValueEventArgs e)
        {

            base.OnQueryProgressValue(e);
            if (!this.View.Session.ContainsKey(ProcessRateValue))
            {
                this.View.Session.Add(ProcessRateValue, 0);
            }
            // 更新进度条
            e.Value = (int)this.View.Session[ProcessRateValue];
            if (e.Value >= 100)
            {
                this.View.GetControl("F_RDLV_YSCBCX").Visible = true;//显示链接
            }

        }

        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            switch (e.Key.ToUpper())
            {
                case "F_RDLV_YSCBCX":   //点击"预算成本查询"链接

                    //BillShowParameter g_aBParameter = new BillShowParameter();
                    //g_aBParameter.FormId = "RDLV_BugCostTree";    //预算成本树形查询
                    //g_aBParameter.ParentPageId = this.View.PageId;
                    //g_aBParameter.CustomParams.Add("F_RDLV_ORGID", OrgId);
                    //g_aBParameter.CustomParams.Add("F_RDLV_Year", year);
                    //g_aBParameter.CustomParams.Add("F_RDLV_Month", Month);
                    //this.View.ShowForm(g_aBParameter);
                    ListShowParameter showParam = new ListShowParameter();
                    showParam.Context = this.Context;
                    showParam.OpenStyle.ShowType = ShowType.MainNewTabPage;
                    showParam.PageId = Guid.NewGuid().ToString();
                    showParam.FormId = "RDLV_BugCostTree";  //单据标识
                    showParam.IsShowApproved = true; //已审核的单据
                    showParam.IsLookUp = true;
                    showParam.ListFilterParameter.Filter = "F_RDLV_ORGID='" + OrgId + "' and F_RDLV_Year='" + year + "' and F_RDLV_Month='" + Month + "'";
                    //showParam.OpenStyle.ShowType = ShowType.Modal;
                    this.View.ShowForm(showParam);
                    break;
            }
        }
    }
}